package com.example.home.view;

import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.common.gamedetail.GameDetailActivity;
import com.example.home.IStartGameDetailActivity;
import com.example.home.R;
import com.example.home.RecommendRAdapter;
import com.example.common.component.RecyclerOnScrollListener;
import com.example.home.viewmodel.HomeRecommendViewModel;
import com.example.home.viewmodel.HomeViewModel;

import org.jetbrains.annotations.NotNull;

public class HomeRecommendFragment extends Fragment {

    private static final String TAG = "HomeRecommendFragment";
    private HomeRecommendViewModel viewModel;
    private RecyclerView recyclerView;
    RecommendRAdapter recommendRAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;//刷新页面

    public static HomeRecommendFragment newInstance() {
        return new HomeRecommendFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        Log.i(TAG, "onCreateView: ");
        return inflater.inflate(R.layout.home_recommend_fragment, container, false);
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView = view.findViewById(R.id.home_recommend_recyclerview);
        swipeRefreshLayout = view.findViewById(R.id.home_recommend_swipeRefresh);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Log.i(TAG, "onActivityCreated: HomeRecommendFragment");
        super.onActivityCreated(savedInstanceState);
        viewModel = new ViewModelProvider(requireActivity()).get(HomeRecommendViewModel.class);
        // TODO: Use the ViewModel

        //recyclerView的路由创建
        recommendRAdapter = new RecommendRAdapter(viewModel,this.requireContext());
        //设置路由和布局，缺一不可
        recyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));
        recyclerView.setAdapter(recommendRAdapter);

        //绑定路由的点击事件
        recommendRAdapter.iStartGameDetailActivity = new IStartGameDetailActivity() {
            @Override
            public void openById(Integer id) {
                Intent intent = new Intent(requireActivity(), GameDetailActivity.class);
                intent.putExtra("ID", id);
                startActivity(intent);
            }
        };

        //下拉刷新条颜色
        swipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(requireActivity(), R.color.theme_color));
        //下拉刷新监听
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //放置加载数据——Start
                viewModel.loadTop();
            }
        });

        //监听下拉加载
        viewModel.getIsLoadDone().observe(requireActivity(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    recommendRAdapter.notifyItemRangeInserted(0, HomeRecommendViewModel.LOAD_NUMBER);
                    swipeRefreshLayout.setRefreshing(false);
                    //加载完成后移动到某个位置
                    recyclerView.smoothScrollToPosition(0);
                }
            }
        });

        //监听上拉加载
        viewModel.getIsLoadDownDone().observe(requireActivity(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    recommendRAdapter.notifyItemRangeInserted(recommendRAdapter.getItemCount()
                            , HomeRecommendViewModel.LOAD_NUMBER);
                }
            }
        });


        //上拉监听
        recyclerView.addOnScrollListener(new RecyclerOnScrollListener() {
            @Override
            public void loadMore() {
                viewModel.loadDown();
            }

            @Override
            public void showTopData(int position) {
            }
        });

        //首次刷新
        if (viewModel.isFirstLoad) {
            //刚进页面时显示加载条
            swipeRefreshLayout.setRefreshing(true);
            viewModel.loadTop();
            viewModel.isFirstLoad=false;
        }

        //切换刷新
        freshShow();

    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i(TAG, "onPause: ");
        swipeRefreshLayout.setRefreshing(false);
        viewModel.isFirstLoad = false;
    }

    public void freshShow(){
        LinearLayoutManager manager=(LinearLayoutManager)recyclerView.getLayoutManager();
        if(manager==null) {
            Log.i(TAG, "freshShow: return");
            return;
        }
        //获取头部和顶部的item
        int head=manager.findFirstVisibleItemPosition();
        int end=manager.findLastVisibleItemPosition();
        recommendRAdapter.notifyItemRangeChanged(head,3);
        Log.i(TAG, "freshShow: ");
    }
}